<?php

namespace app\api\controller;

use app\facade\Redis;
use think\Validate;
use app\models\{Region, Cate, Subcate, Product, Banner, Cart, Config, Wechat, Annous, Riderlist, Douyin, Promo, Agent, AgentArea};
use think\facade\Env;
use think\Db;
use oss\Oss;
use think\facade\Log;
use think\db\Where;
use EasyWeChat\Factory;


class Other extends Base
{

    public function comobo()
    {
        $list = (new Promo())->field('id,title,descs,images,money')->where(['status' => 1, 'type' => 2, 'agentid' => 0])->select();
        $this->result($list, 0, '获取成功');
    }

    public function  riderauth()
    {
        return view();
    }

    public function  riderauth2()
    {
        $data = $this->request->get();
        $validate = new Validate([
            'code' => 'require',
            'mobile' => 'require'
        ], [
            'code.require' => 'code不能为空',
            'mobile.require' => '师傅账号不能为空'
        ]);
        if (!$validate->check($data)) {
            return $validate->getError();
        }
        $user = (new Riderlist())->where(['mobile' => $data['mobile']])->find();
        if (empty($user)) {
            return view(null, ['list' => ['status' => 1, 'info' => '骑手账号不存在,请确保手机号码正确!']]);
        }
        $config = config('wechat1.');
        try {
            $app = Factory::officialAccount($config);
            $wxuser = $app->oauth->user();
            if (!empty($wxuser['id'])) {
                $wuser = $app->user->get($wxuser['id']);
                if (empty($wuser['subscribe']) || $wuser['subscribe'] != 1) {
                    return view(null, ['list' => ['status' => 1, 'info' => '授权前请先关注[铛铛洗鞋]公众号!']]);
                }
                if ($user['openid'] == $wxuser['id']) {
                    return view(null, ['list' => ['status' => 1, 'info' => '您已授权!']]);
                }
                $res = (new Riderlist())->where(['id' => $user['id']])->update(['openid' => $wxuser['id']]);
                if (!$res) {
                    return view(null, ['list' => ['status' => 1, 'info' => '授权失败!']]);
                }
                //进行通知
                $appid = config('wechat.')['app_id'] ?? '';
                $data = [
                    'first' => [
                        'value' => '新订单通知，请前往处理订单'
                    ],
                    'keyword1' => [
                        'value' => time()
                    ],
                    'keyword2' => [
                        'value' => rand(100, 9999)
                    ],
                    'keyword3' => [
                        'value' => date('Y-m-d H:i:s')
                    ],
                    'remark' => [
                        'value' => '本通知为订阅成功后发送的测试消息!'
                    ],
                ];
                wechatmessage($wxuser['id'], 'Orv7eAKo79EsndDowfcoG87JT7p5qQhSJ4KnDFoxDxc', $data, $appid, '/pages/horseman/index');
                return view(null, ['list' => ['status' => 0, 'info' => '授权成功!']]);
            }
        } catch (\Exception $e) {
            return view(null, ['list' => ['status' => 1, 'info' => '授权失败!']]);
            // return $e->getMessage();
        }
    }

    public function getconfig()
    {
        $name = $this->request->get('name/s', 0);
        $list = (new Config())->where('name', $name)->value('value') ?? '';
        $this->result($list, 0, '获取成功');
    }

    public function banner()
    {
        $streetid = $this->request->get('streetid/d', 0);
        $types = $this->request->get('types/d', 1);
        $data['lat'] = $this->request->get('lat') ?? 0;
        $data['lng'] = $this->request->get('lng') ?? 0;
        Log::write($data, 'getlons');
        $agentid = getlatlon($data['lat'], $data['lng'], 1);
        if (empty($agentid)) {
            $agentid = getdrees($streetid, 1);
        }
        $yyopen = (new Agent())->where('id', $agentid)->value('yyopen') ?? 1; //一元洗鞋开关  1关 2开
        $list = (new Banner())->order('sort desc')->where(['agentid' => [0, $agentid], 'types' => $types])->field('id,title,url,appid');
        if ($yyopen == 1) {
            $list = $list->where(['isopen' => 1]);
        }
        $list = $list->select();
        $this->result($list, 0, '获取成功');
    }

    public function annous()
    {
        $streetid = $this->request->get('streetid/d', 0);
        $data['lat'] = $this->request->get('lat') ?? 0;
        $data['lng'] = $this->request->get('lng') ?? 0;
        Log::write($data, 'getlons');
        $agentid = getlatlon($data['lat'], $data['lng'], 1);
        if (empty($agentid)) {
            $agentid = getdrees($streetid, 1);
        }
        $list = (new Annous())->where(['agentid' => $agentid])->order('id desc')->field('id,title,types,content')->find();
        $this->result($list, 0, '获取成功');
    }

    public function oss()
    {
        if ($this->request->isPost()) {
            if (Env::get('aliyun.open')) {
                $file =  $_FILES['file'] ?? '';
                if (empty($file)) {
                    $this->result([], 1, '请选择上传图片');
                }
                $oss = new Oss();
                $oss->setUploadType('ram');
                $url = $oss->uploadPostFile($file, 'duangduang/' . date('Y-m-d'));
                $this->result($url, 0, '获取成功');
                $result = [];
                try {
                    $result = (new Oss())->getCredentials();
                    $result['regionId'] = Env::get('aliyun.regionId');
                    $result['bucket'] = Env::get('aliyun.bucket');
                    $result['endpoint'] = Env::get('aliyun.endpoint');
                } catch (\Exception $e) {
                    $this->result([], 1, $e->getMessage());
                }
                $this->result($result, 0, '获取成功');
            } else {
                $file = request()->file('file');
                $path =  $_SERVER['DOCUMENT_ROOT'] . "/uploads/";
                $info = $file->validate(['ext' => 'jpg,png,gif,jpeg'])
                    ->move($path);
                if (!$info) {
                    $this->result([], 1, $file->getError());
                } else {
                    $file_edit = $info->getInfo();
                    $url = './uploads' . '/' . date("Ymd") . '/' . $info->getfileName();
                    if ($file_edit['size'] > 204800) { // 大于100K的图片进行处理
                        // 获取上传的图片，进行图片压缩
                        $image = \think\Image::open($info);
                        // 保存图片的路径处理
                        $image->thumb(1400, 1400)->save($url);
                    }
                    $url = url($url, '', '', false);
                    $url = "https://" . Env('app.api_url') . $url;
                    $this->result($url, 0, '获取成功');
                }
            }
        }
    }

    //高德接口
    public function getstreet()
    {
        $key = env('map.key');
        if ($this->request->isGet()) {
            $data = $this->request->get();
            $validate = new Validate([
                'lat' => 'require',
                'lng' => 'require',
            ], [
                'lat.require' => '纬度必须填写',
                'lng.require' => '经度必须填写',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $url = 'https://restapi.amap.com/v3/geocode/regeo';
            $res = api_curl($url, ['location' => $data['lng'] . ',' . $data['lat'], 'key' => $key, 'extensions' => 'all']);
            Log::write($data, 'getstreet');
            if ($res['status'] == 1) {
                if (empty($res['regeocode']['addressComponent'])) {
                    $this->result([], 1, '请求失败,请重试');
                }
                $results = $res['regeocode']['addressComponent'];
                //街道查不到重新请求
                if (empty($results['township'])) {
                    $data['lng'] = floor($data['lng'] * 10000) / 10000;
                    $data['lat'] = floor($data['lat'] * 10000) / 10000;
                    $res = api_curl($url, ['location' => $data['lng'] . ',' . $data['lat'], 'key' => $key, 'extensions' => 'all']);
                    if ($res['status'] == 1) {
                        if (empty($res['regeocode']['addressComponent'])) {
                            $this->result([], 1, '请求失败,请重试');
                        }
                        $results = $res['regeocode']['addressComponent'];
                    }
                }
                $add = $res['regeocode']['aois'][0]['name'] ?? '';
                if (empty($add)) {
                    $add = $res['regeocode']['pois'][0]['name'] ?? '';
                }
                $resuls = [
                    "adcode" => !empty($results['adcode']) ? $results['adcode'] : 0,
                    "province" => !empty($results['province']) ? $results['province'] : '未知省份',
                    "city" => !empty($results['city']) ? $results['city'] : '未知城市',
                    "district" => !empty($results['district']) ? $results['district'] : '未知区域',
                    "street" => 0,
                    "street_title" => !empty($results['township']) ? $results['township'] : '未知街道',
                    'address' => $add ?? '',
                    'formatted_address' => $res['regeocode']['formatted_address'] ?? ''
                ];
                $results['towncode'] = !empty($results['towncode']) ? $results['towncode'] : 0;
                $resuls['city'] = empty($resuls['city']) ? $resuls['province'] : $resuls['city'];
                $street_id = (new Region())
                    ->where(['level' => 4])
                    ->where('area_code', $resuls['adcode'])
                    ->where('name|remark', 'like', '%' . $resuls['street_title'] . '%')->find();
                //长名字查找不到 缩减名字查找
                $township = mb_substr($resuls['street_title'], 0, 2, 'utf-8');
                if (empty($street_id['id'])) {
                    $street_id = (new Region())
                        ->where(['level' => 4])
                        ->where('area_code', $resuls['adcode'])
                        ->where('name|remark', 'like', '%' . $township . '%')->find();
                }
                //通过名字查找不到街道再通过编号查找
                if (empty($street_id['id'])) {
                    $street_id = (new Region())
                        ->where(['level' => 4])
                        ->where('area_code', $resuls['adcode'])
                        ->where('code', substr($results['towncode'] ?? 0, 0, 9))->find();
                }
                $resuls['street'] = $street_id['id'] ?? 0;
                $resuls['street_title'] = $street_id['name'] ?? $resuls['street_title'];
                // //插入街道
                if (empty($resuls['street']) && !empty($resuls['adcode'])) {
                    $insertregion = (new Region())->where(['level' => 3, 'area_code' => $resuls['adcode']])->value('id');
                    if ($insertregion > 0) {
                        $resuls['street'] = (new Region())->insertGetId(
                            [
                                'parent_id' => $insertregion,
                                'level' => 4,
                                'name' => $resuls['street_title'],
                                'area_code' => $resuls['adcode'],
                                'code' => $resuls['adcode'] * 1000
                            ]
                        );
                    }
                }
                Log::write($resuls, 'getstreet');
                $this->result($resuls, 0, '获取成功');
            } else {
                $this->result([], 1, '请求失败');
            }
        } else {
            $this->result([], 0, ['key' => $key]);
        }
    }

    public function street()
    {
        $areacode = $this->request->get('areacode/d', 0);
        $list = (new Region())->where('area_code', $areacode)->where(['level' => 4])->select();
        $this->result($list, 0, '获取成功');
    }

    public function addressjson()
    {
        $addressjsonredis = 'addressjsonredis';
        $haveaddress = Redis::get($addressjsonredis);
        if ($haveaddress) {
            $result = unserialize($haveaddress);
        } else {
            $region = (new Region())->field('name as label,area_code as value,id,parent_id,level')->where(['level' => [1, 2, 3]])->select();
            $resultson = [];
            $results = [];
            $result = [];
            foreach ($region as $regions) {
                if ($regions['level'] == 3) {
                    $resultson[$regions['parent_id']][] = [
                        'label' => $regions['label'],
                        'value' => $regions['value']
                    ];
                }
            }
            foreach ($region as $regions) {
                if ($regions['level'] == 2) {
                    $results[$regions['parent_id']][] = [
                        'label' => $regions['label'],
                        'value' => $regions['value'],
                        'children' => $resultson[$regions['id']] ?? []
                    ];
                }
            }
            foreach ($region as $regions) {
                if ($regions['level'] == 1) {
                    $result[] = [
                        'label' => $regions['label'],
                        'value' => $regions['value'],
                        'children' => $results[$regions['id']] ?? []
                    ];
                }
            }
            Redis::setex($addressjsonredis, 60 * 60 * 3, serialize($result));
        }
        return json($result);
    }

    public function cate()
    {
        $list =  (new Cate())->order(['sort' => 'desc', 'id' => 'desc'])->where(['isshow' => 1])->field('id,name,images')->select();
        $this->result($list, 0, '获取成功');
    }

    public function subcate()
    {
        $streetid = $this->request->get('streetid/d', 0);
        $cate = $this->request->get('cate/d', 0);
        if (empty($streetid)) {
            $agentid = (new AgentArea())->alias('ar')
                ->join('agent a', 'ar.agentid = a.id')
                ->where(['a.status' => 1, 'ar.type' => 1])
                ->value('a.id') ?? 0;
        } else {
            //获取街道区域代理ID
            $agentid = getdrees($streetid, 1);
        }
        $list =  (new Subcate())
            ->order(['sort' => 'desc', 'id' => 'asc'])
            ->where(['isshow' => 1, 'agentid' => $agentid])->field('id,name,images');
        if (!empty($cate)) {
            $list = $list->where('cate', $cate);
        }
        $list = $list->select();
        $user_id = $this->request->user_id ? $this->request->user_id : 0;
        $user_dict = $this->request->user_dict ? $this->request->user_dict : 100;
        $agentinfo = (new Agent())->where('id', $agentid)->find();
        if (!empty($agentinfo) && $agentinfo['levelopen'] == 2) {
            $user_dict = $agentinfo['levelrate'] ?? 100;
        }
        $result = [];
        //全部产品
        $productss = (new Product())->alias('p')
            ->order(['p.sort' => 'desc', 'p.id' => 'desc'])
            ->leftjoin('cart c', ['c.user_id = ' . $user_id, 'c.productid = p.id'])
            ->where(['p.isdel' => 1, 'p.isshow' => 1, 'p.agentid' => $agentid, 'p.cate' => $cate])
            ->field('p.id,p.title,p.descs,p.images,p.price,ifnull(c.id,0) as cartid,ifnull(c.number,0) as number')
            ->select();
        foreach ($productss as $product) {
            $product['dictprice'] = floor((floor($product['price'] * $user_dict * 100) / 10000) * 100) / 100;
        }
        $result[0] = [
            'id' => $cate - 9999999,
            'name' => '全部',
            'images' => '',
            'product' => $productss
        ];
        foreach ($list as $k => $row) {
            $row['product'] =  (new Product())->alias('p')
                ->order(['p.sort' => 'desc', 'p.id' => 'desc'])
                ->leftjoin('cart c', ['c.user_id = ' . $user_id, 'c.productid = p.id'])
                ->where(['p.isdel' => 1, 'p.isshow' => 1, 'p.agentid' => $agentid, 'p.subcate' => $row['id']])
                ->field('p.id,p.title,p.descs,p.images,p.price,ifnull(c.id,0) as cartid,ifnull(c.number,0) as number')
                ->select();
            foreach ($row['product'] as $product) {
                $product['dictprice'] = floor((floor($product['price'] * $user_dict * 10) / 1000) * 100) / 100;
            }
            $result[$k + 1] = $row;
        }
        $this->result($result, 0, '获取成功');
    }

    public function product()
    {
        $streetid = $this->request->get('streetid/d', 0);
        if (empty($streetid)) {
            $this->result('', 0, '获取成功');
        }
        $cate = $this->request->get('cate/d', 0);
        $subcate = $this->request->get('subcate/d', 0);
        $ishot = $this->request->get('ishot/d', 1);
        $title = $this->request->get('title/s', '');
        //获取街道区域代理ID
        $data['lat'] = $this->request->get('lat') ?? 0;
        $data['lng'] = $this->request->get('lng') ?? 0;
        Log::write($data, 'getlons');
        $agentid = getlatlon($data['lat'], $data['lng'], 1);
        if (empty($agentid)) {
            $agentid = getdrees($streetid, 1);
        }
        if (empty($agentid)) {
            $this->result('', 0, '获取成功');
        }
        $list =  (new Product())
            ->where(['isdel' => 1, 'isshow' => 1, 'agentid' => $agentid])
            ->field('id,title,images,price,descs,cate,subcate');
        if (!empty($cate)) {
            $list = $list->where('cate', $cate);
        }
        if (!empty($title)) {
            $list = $list->where('title', 'like', '%' . $title . '%');
        }
        if (!empty($ishot) && $ishot == 2) {
            $list = $list->order(['ishot' => 'desc']);
        }
        if (!empty($subcate)) {
            if ($subcate < 0) {
                // $list = $list->where('cate', ($subcate + 9999999));
            } else {
                $list = $list->where('subcate', $subcate);
            }
        }
        $list = $list->order(['sales' => 'desc', 'sort' => 'desc'])->select();
        $user_id = $this->request->user_id ? $this->request->user_id : 0;
        $user_dict = $this->request->user_dict ? $this->request->user_dict : 100;
        $agentinfo = (new Agent())->where('id', $agentid)->find();
        if (!empty($agentinfo) && $agentinfo['levelopen'] == 2) {
            $user_dict = $agentinfo['levelrate'] ?? 100;
        }
        foreach ($list as $product) {
            $cart = (new  Cart())->where(['user_id' => $user_id, 'productid' => $product['id']])->field('id,number')->find();
            $product['cartid'] = $cart['id'] ?? 0;
            $product['number'] = $cart['number'] ?? 0;
            $product['dictprice'] = floor((floor($product['price'] * $user_dict * 100) / 10000) * 100) / 100;
        }
        $this->result($list, 0, '获取成功');
    }

    //支付回调结果
    public function callback()
    {
        $type = input('type/d');
        if (!empty($type) && $type == 2) {
            $result = (new Douyin())->callback();
        } else {
            $result = (new Wechat())->callback();
        }
        Log::write($result, 'refund');
        if ($result['msg'] == 'success') {
            return 'SUCCESS';
        }
        return false;
    }

    //微信取消订单回调结果
    public function callback2()
    {
        $result = (new Wechat())->callback2();
        Log::write($result, 'refund');
        if ($result['msg'] == 'success') {
            return 'SUCCESS';
        }
        return false;
    }

    //微信取消订单回调结果
    public function callback3()
    {
        $result = (new Douyin())->callback2();
        Log::write($result, 'refund');
        if ($result['msg'] == 'success') {
            return 'SUCCESS';
        }
        return false;
    }


    public function getopenid()
    {
        $data = $this->request->get();
        $validate = new Validate([
            'agentid' => 'require',
            'code' => 'require',
            'state' => 'require'
        ], [
            'agentid.require' => '账号ID不能为空',
            'code.require' => 'code必须填写',
            'state.require' => '链接编码错误，请重新扫码或刷新页面扫码',
        ]);
        if (!$validate->check($data)) {
            $results = ['status' => 1, 'info' => $validate->getError()];
            return view(null, ['list' => $results]);
        }
        $name = 'getopenidagent' . $data['agentid'];
        $code = Redis::get($name);
        if($code != $data['state']){
            $results = ['status' => 1, 'info' => '请重新扫码或刷新页面重新扫码'];
            return view(null, ['list' => $results]);
        }
        $agent = (new Agent())->where('id', $data['agentid'])->find();
        if (empty($agent)) {
            $results = ['status' => 1, 'info' => '授权失败,用户不存在'];
            return view(null, ['list' => $results]);
        }
        $config = config('wechat1.');
        try {
            $app = Factory::officialAccount($config);
            $result = $app->oauth->user();
            if ($agent['openid'] == $result['id']) {
                $res = true;
            } else {
                $res = (new Agent())->where('id', $agent['id'])->update(['openid' => $result['id']]);
            }
            if (!$res) {
                $results = ['status' => 1, 'info' => '授权失败,请重试'];
                return view(null, ['list' => $results]);
            }
            $results = ['status' => 0, 'info' => '授权成功!'];
            return view(null, ['list' => $results]);
        } catch (\Exception $e) {
            $results = ['status' => 1, 'info' => $e->getMessage()];
            return view(null, ['list' => $results]);
        }
        $results = ['status' => 1, 'info' => '授权失败,请重试'];
        return view(null, ['list' => $results]);
    }
}
